/**
 * @author: gao
 * @create-date: 2025/3/15 14:06
 */

public class HashBucket {
    //创建节点数组
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array = new Node[10];
    public int UsedSize;//表示还系统中存放的元素
    public static final float LOAD_FACTOR = 0.75f;//负载因子表示为常数

    //放元素
    public void put(int key, int val) {
        int index = key % array.length;

        //先遍历index数组下的链表，如果有相同的key，则更新val
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        //头插法
        Node node = new Node(key, val);
        node.next = array[index];
        array[index] = node;
        UsedSize++;

        //重新计算负载因子是不是超过了我们规定的值
        if (CalculateLoadFactor() >= LOAD_FACTOR) {
            //扩容
            ReSize();
        }
    }

    private float CalculateLoadFactor() {
        return UsedSize * 1.0f / array.length;
    }

    private void ReSize() {
        Node[] newArray = new Node[array.length*2];
        for (Node node : array) {
            Node cur = node;
            while (cur != null) {
                int newIndex = cur.key % newArray.length;
                //把当前节点放入新数组的位置,再次使用头插法
                Node curNext = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curNext;
            }
        }
        array = newArray;
    }

    public int get(int key){
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}